from TikTokApi import TikTokApi
import json
import os
import random
did = str(random.randint(10000, 999999999))

proxy="http://scraperapi:7383d26700b0269bfe37eaadc1eab541@proxy-server.scraperapi.com:8001"
proxy="http://208.80.28.208:8080"
verifyfp="verify_07bd24eb869bc9516ffd95b22194cb97"
api = TikTokApi.get_instance()

i=0
j=0
########
ht='homemade'
########
#baseballtiktok
#cartiktok
#competitivegaming
#coversforlovers
#crowdcheers
#dailyvlog
#dayandnight
#defrosting
#dinnerparty
#diyprojects
#doctorsoftiktok
#downsyndromeday
#dramaticmoments
#earthday
#easyrecipe
#ecohacks
#emophase
#fantheory
#feelinggood
#feliznavidad
#fetapasta
#fitnesslife
#foodie
#foodontiktok
#galentinesday
#gamergoals
#gamingtiktok
#gettheretogether
#givethanksnotpranks
#glasspainting????
#goodmorning
#GreenScreenScan？？？？？
#groupchat
#guitartok
#happyeaster
#happyholi



#fitnessroutine
#givethanksnotpranks
#healthycooking
#healthyheart
##healthyliving
#hellospring
#herstory
#holidaytreats
#homebusiness
#homecafe
#homecook
#homediy
#homeimprovement
#homemade
#homeproject
##hyperfixated
#imbusyrightnow
#inlove
#inspirationalquotes
#Inverted
#isthisavailable
#itwasntaphase
#joblife
#joedizzle
#kissyourpet
#laughingduet
#learnontiktok
#learnwithme
#Lifestyle
#lookbook
#loveyourinsecurities
#makeblackhistory
#marchmadness
#meditation101
#melaninmagic
#mifamilia
#mlkday
#mobilegame#
#moneytok
#myhaul
#myroutine
#mystyle
#naturescereal
#nbaallstar
#nbaisback
#neontwin
#nflplayoffs
#NHLFaceOff
#notaperfectperson#
#nowlookatthis
#nowruz
#OhNo
#OlympicsCountdown
#oneyourthere
#ontherunway
#oscars
#passingthephone
#passover
#perfectdrink
#perfectgifts
#petsontiktok
#plantparent
#pleasedontgo
##problemstop
#projectcar
#promszn
#puppiesonly
#puppybowl
#RamadanMubarak
#rareaesthetic
#RatatouilleMusical
#relationshipstorytime
#roundofapplause
#RoyalRumble
#SabiasQue
##science101
#seashanty
#sehablaespañol
#seitan
#sheearnedit
##sheesh
#siblinggoals
#sidetable
#skincare101
#snowstorm#
#somethingyoulearned
#songfacts
#springoutfit
#springvibes
#stepbystep
#stopasianhate
#stpatricksday
#stylehacks#
#superbowllv
#syndouch1
#takeabite
######takeout
#thankstoher
#thegirlashley4
#thriftflip
##thrifting
######tiktokcars
#tiktokdiy
########tiktokfashionmonth
#tiktokfitness
#tiktoktailgate
#tiktoktutorial
#tiktokwildlifeday
#timewarpjump
#timewarpwaterfall
#tipsandtricks
#tortillatrend
#transvisibilityday
#typing
#UnwrapTheDeals
#upcycling
#vaccinatedfor
#valentinesdiy
#vinylclub
#visionboard
#watchingxfactor
#wee
#weirdpets
#welcome2021
#whatilearned
#whenwomenwin
#winterbeautytips
#winterfashion
#winterfit
#WinterMagic
#wintersports
#withouttellingme
#womeninsports
#@womeninstem
#WordsOfWisdom
#wrappinggifts
#wrestlemania
#xgamesmode
#YearOnTikTok
#yoga101
#zodiacsign
for file in os.listdir('D:\\Work\\Tool\\tiktok\\TikToks\\'):
    if not file.endswith('.json'):
        continue
    if ht in file:
        if os.path.exists('E:\\tiktok\\Hashtag\\'+ht):
            pass
        else:
            os.mkdir('E:\\tiktok\\Hashtag\\'+ht)
        with open('D:\\Work\\Tool\\tiktok\\TikToks\\' + file, 'r', encoding='utf-8', newline='\n') as filename_input:
            with open('E:\\Tiktok\\error_tk1.txt', 'w') as filename_output:
                for line in filename_input:
                    z = json.loads(line)
                    k=''
                    if 'id' in z.keys():
                        k=z['id']
                    elif 'itemInfos' in z.keys():
                        k=z['itemInfos']['id']
                    if os.path.exists('E:\\tiktok\\Hashtag\\'+ht+'\\'+k+'.mp4'):
                        continue
                    else:
                        did = str(random.randint(10000, 999999999))
                        tk = api.getTikTokById(k,custom_did=did)
                        if 'itemInfo' not in tk.keys() and 'itemInfos' not in tk.keys():
                            i+=1
                            print('Hashtag',ht,k,'cannot be retrived', tk,'Total:',i)
                            continue
                        try:
                            tiktokData=api.get_Video_By_TikTok(tk,custom_did=did)
                            if tiktokData.startswith(b'<HTML><HEAD>\n<TITLE>Access Denied'):
                                j += 1
                                print('Hashtag', ht, k, 'Access Denied', tk, 'Total:', j)
                                continue
                            else:
                                with open(
                                        'E:\\tiktok\\' + 'Hashtag' + '\\' + ht + '\\' + k + '.mp4',
                                        'wb') as out:
                                    out.write(tiktokData)
                                print('Hashtag', ht, k, 'successful download')
                        except:
                            print('----------')
                            print('ERROR')
                            print(k)
                            filename_output.write(k+'\n')
                            print('----------')



# for file in os.listdir('D:\\Work\\Tool\\tiktok\\tiktoktest\\'):
#     with open('D:\\Work\\Tool\\tiktok\\tiktoktest\\' + file, 'r', encoding='utf-8', newline='\n') as filename_input:
#         for line in filename_input:
#             z = json.loads(line)
#             did = str(random.randint(10000, 999999999))
#             tk=api.getTikTokById(z['itemInfos']['id'],custom_did=did)
#             tiktokData=api.get_Video_By_TikTok(tk,custom_did=did)
#             print(tiktokData)fitnesslife
#             # tiktokData1=api.get_Video_By_DownloadURL(api.getTikTokById(z['itemInfos']['id'])['itemInfo']['itemStruct']['video']['downloadAddr'])
#             # print(tiktokData1)
#             break
#
#
#
# did = str(random.randint(10000, 999999999))
# tiktoks = api.trending(custom_did=did)
# print(tiktoks[0])
# b = api.get_Video_By_TikTok(tiktoks[0], custom_did=did)
# with open('E:\\Tiktok\\test.mp4', 'wb') as out:
#     out.write(b)
# print(b)